package com.ruoyi.reportInfo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.reportInfo.domain.IndustrialLogisticsCompany;
import com.ruoyi.reportInfo.domain.IndustrialLogisticsCompanyLineOperation;
import com.ruoyi.reportInfo.domain.bo.IndustrialLogisticsCompanyBo;
import com.ruoyi.reportInfo.domain.vo.IndustrialLogisticsCompanyVo;
import com.ruoyi.reportInfo.mapper.IndustrialLogisticsCompanyLineOperationMapper;
import com.ruoyi.reportInfo.mapper.IndustrialLogisticsCompanyMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.reportInfo.domain.bo.IndustrialLogisticsCompanyLineBo;
import com.ruoyi.reportInfo.domain.vo.IndustrialLogisticsCompanyLineVo;
import com.ruoyi.reportInfo.domain.IndustrialLogisticsCompanyLine;
import com.ruoyi.reportInfo.mapper.IndustrialLogisticsCompanyLineMapper;
import com.ruoyi.reportInfo.service.IIndustrialLogisticsCompanyLineService;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 物流企业专线信息Service业务层处理
 *
 * @author yangzhen
 * @date 2025-11-24
 */
@RequiredArgsConstructor
@Service
public class IndustrialLogisticsCompanyLineServiceImpl implements IIndustrialLogisticsCompanyLineService {

    private final IndustrialLogisticsCompanyLineMapper baseMapper;

    private final IndustrialLogisticsCompanyMapper industrialLogisticsCompanyMapper;

    private final IndustrialLogisticsCompanyLineOperationMapper industrialLogisticsCompanyLineOperationMapper;

    /**
     * 查询物流企业专线信息
     */
    @Override
    public IndustrialLogisticsCompanyLineVo queryById(String id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询物流企业专线信息列表
     */
    @Override
    public TableDataInfo<IndustrialLogisticsCompanyLineVo> queryPageList(IndustrialLogisticsCompanyLineBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<IndustrialLogisticsCompanyLine> lqw = buildQueryWrapper(bo);
        Page<IndustrialLogisticsCompanyLineVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    @Override
    public TableDataInfo<IndustrialLogisticsCompanyLineVo> industrialCompanyLinePageList(
        IndustrialLogisticsCompanyLineBo bo, PageQuery pageQuery) {

        LambdaQueryWrapper<IndustrialLogisticsCompanyLine> lqw = buildQueryWrapper(bo);

        // 1. 分页查询专线基本信息
        Page<IndustrialLogisticsCompanyLineVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);

        List<IndustrialLogisticsCompanyLineVo> records = result.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return TableDataInfo.build(result);
        }

        // 2. 获取今年年份
        int currentYear = LocalDate.now().getYear();

        // 3. 批量获取 companyIds
        List<String> companyIds = records.stream()
            .map(IndustrialLogisticsCompanyLineVo::getCompanyId)
            .collect(Collectors.toList());

        // 4. 查询公司信息并构造成 map
        List<IndustrialLogisticsCompany> companies = industrialLogisticsCompanyMapper.selectList(
            Wrappers.<IndustrialLogisticsCompany>lambdaQuery().in(IndustrialLogisticsCompany::getId, companyIds)
        );

        Map<String, IndustrialLogisticsCompany> companyMap = companies.stream()
            .collect(Collectors.toMap(IndustrialLogisticsCompany::getId, c -> c));

        // =============================================================
        // 5. 循环专线，填充公司信息 + 本年度运营统计
        // =============================================================
        for (IndustrialLogisticsCompanyLineVo line : records) {

            // ------------------------------------------------------------
            // 5.1 关联企业信息
            // ------------------------------------------------------------
            IndustrialLogisticsCompany company = companyMap.get(line.getCompanyId());
            if (company != null) {
                line.setCompanyName(company.getCompanyName());
            }

            // ------------------------------------------------------------
            // 5.2 查询专线运营信息（按：companyId + 起点 + 终点 + 年份）
            // ------------------------------------------------------------
            List<IndustrialLogisticsCompanyLineOperation> opList =
                industrialLogisticsCompanyLineOperationMapper.selectList(
                    Wrappers.<IndustrialLogisticsCompanyLineOperation>lambdaQuery()
                        .eq(IndustrialLogisticsCompanyLineOperation::getCompanyId, line.getCompanyId())
                        .eq(IndustrialLogisticsCompanyLineOperation::getStartPoint, line.getStartPoint())
                        .eq(IndustrialLogisticsCompanyLineOperation::getEndPoint, line.getEndPoint())
                        .apply("YEAR(report_collect_date) = {0}", currentYear)
                );

            // ------------------------------------------------------------
            // 5.3 统计本年度货运量 annualCargoVolume
            // ------------------------------------------------------------
            BigDecimal totalCargo = opList.stream()
                .map(IndustrialLogisticsCompanyLineOperation::getFreightVolume)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

            line.setAnnualCargoVolume(totalCargo);
        }

        return TableDataInfo.build(result);
    }

    /**
     * 查询物流企业专线信息列表
     */
    @Override
    public List<IndustrialLogisticsCompanyLineVo> queryList(IndustrialLogisticsCompanyLineBo bo) {
        LambdaQueryWrapper<IndustrialLogisticsCompanyLine> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<IndustrialLogisticsCompanyLine> buildQueryWrapper(IndustrialLogisticsCompanyLineBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<IndustrialLogisticsCompanyLine> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getCompanyId()), IndustrialLogisticsCompanyLine::getCompanyId, bo.getCompanyId());
        lqw.eq(StringUtils.isNotBlank(bo.getStartPoint()), IndustrialLogisticsCompanyLine::getStartPoint, bo.getStartPoint());
        lqw.eq(StringUtils.isNotBlank(bo.getEndPoint()), IndustrialLogisticsCompanyLine::getEndPoint, bo.getEndPoint());
        lqw.eq(StringUtils.isNotBlank(bo.getLineType()), IndustrialLogisticsCompanyLine::getLineType, bo.getLineType());
        lqw.eq(bo.getCarCount() != null, IndustrialLogisticsCompanyLine::getCarCount, bo.getCarCount());
        lqw.eq(bo.getProvinceType() != null, IndustrialLogisticsCompanyLine::getProvinceType, bo.getProvinceType());
        lqw.eq(bo.getReportCollectDate() != null, IndustrialLogisticsCompanyLine::getReportCollectDate, bo.getReportCollectDate());
        return lqw;
    }

    /**
     * 新增物流企业专线信息
     */
    @Override
    public Boolean insertByBo(IndustrialLogisticsCompanyLineBo bo) {
        IndustrialLogisticsCompanyLine add = BeanUtil.toBean(bo, IndustrialLogisticsCompanyLine.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改物流企业专线信息
     */
    @Override
    public Boolean updateByBo(IndustrialLogisticsCompanyLineBo bo) {
        IndustrialLogisticsCompanyLine update = BeanUtil.toBean(bo, IndustrialLogisticsCompanyLine.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(IndustrialLogisticsCompanyLine entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除物流企业专线信息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

}
